package org.example;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.io.IOException;
import java.net.URL;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 实时薪资计算器的GUI界面类
 */
public class SalaryCalculatorGUI extends JFrame {
    private static final String DEFAULT_TRAY_ICON = "/images/app_icon.png";
    static final Logger logger = LoggerFactory.getLogger(SalaryCalculatorGUI.class);
    private final SalaryCalculator calculator;
    private final DecimalFormat decimalFormat;
    private Timer updateTimer;

    // GUI组件
    private JComboBox<String> salaryTypeCombo;
    private JTextField salaryField;
    private JLabel salaryTypeLabel;
    private JSpinner workHoursSpinner;
    private JSpinner workDaysSpinner;
    private JButton startButton;
    private JButton pauseButton;
    private JButton endButton;
    private JButton toggleTopButton;
    private JButton miniWindowButton;
    private JLabel todayEarningsLabel;
    private JLabel monthlyEarningsLabel;
    private boolean isWindowTop;
    private MiniEarningsWindow miniWindow;

    // 每小时、每分钟、每秒收益标签
    private JLabel hourlyEarningsLabel;
    private JLabel minuteEarningsLabel;
    private JLabel secondEarningsLabel;

    public SalaryCalculatorGUI() {
        calculator = new SalaryCalculator();
        decimalFormat = new DecimalFormat("¥#,##0.00");
        isWindowTop = false;
        miniWindow = null;

        initializeUI();
        addConfigChangeListeners(); // 配置变更监听
        setupTimer();

        // 在初始化时立即更新UI显示
        updateDisplay();
    }

    private void initializeUI() {
        setTitle("实时薪资计算器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 450);
        setResizable(false); // 禁止窗口调整大小
        setLocationRelativeTo(null);

        // 创建主面板
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        mainPanel.setBorder(new EmptyBorder(10, 20, 20, 20)); // 统一使用适中的边距

        // 先创建所有UI组件
        createEarningsPanel();
        createInputPanel();
        createControlPanel();

        // 初始化薪资计算并显示每小时、每分钟、每秒收益
        Properties config = ConfigManager.loadConfig();
        double salary = Double.parseDouble(config.getProperty("salary", "8000"));
        boolean isMonthly = config.getProperty("salaryType", "月").equals("月");
        int workHours = Integer.parseInt(config.getProperty("dailyWorkHours", "8"));
        double workDays = Double.parseDouble(config.getProperty("monthlyWorkDays", "21.75"));

        calculator.setSalaryInfo(salary, isMonthly, workHours, workDays);
        updateDisplay();

        // 添加各个部分（按照标题->工作设置->收入统计->控制按钮的顺序）
        mainPanel.add(createTitlePanel());
        mainPanel.add(Box.createVerticalStrut(10));
        mainPanel.add(createInputPanel());
        mainPanel.add(Box.createVerticalStrut(10));
        mainPanel.add(createEarningsPanel());
        mainPanel.add(Box.createVerticalStrut(10));
        mainPanel.add(createControlPanel());
        mainPanel.add(Box.createVerticalStrut(10));

        // 设置窗口
        add(mainPanel);

        // 初始化按钮状态
        updateButtonStates(false);

        // 加载上次保存的累计收入数据
        String currentMonth = LocalDate.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM"));
        double savedMonthlyEarnings = MonthlyEarningsRecorder.getEarnings(currentMonth);
        calculator.setInitialMonthlyEarnings(savedMonthlyEarnings);

        // 更新月度收入显示
        monthlyEarningsLabel.setText("本月累计：" + decimalFormat.format(savedMonthlyEarnings));

        try {
            URL iconUrl = getClass().getResource(DEFAULT_TRAY_ICON);
            if (iconUrl != null) {
                Image windowIcon = ImageIO.read(iconUrl);
                setIconImage(windowIcon);
            }
        } catch (IOException e) {
            System.err.println("主窗口图标加载失败: " + e.getMessage());
        }
    }

    private JPanel createTitlePanel() {
        JPanel panel = new JPanel();
        JLabel titleLabel = new JLabel("实时薪资计算器");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(new Color(44, 62, 80));
        panel.add(titleLabel);
        panel.setAlignmentX(Component.CENTER_ALIGNMENT);
        return panel;
    }

    private JPanel createInputPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(52, 152, 219), 1),
                "工作设置",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 14),
                new Color(52, 152, 219)
        ));

        // 加载配置文件
        Properties config = ConfigManager.loadConfig();

        // 薪资输入面板（包含薪资金额和类型）
        JPanel salaryPanel = new JPanel(new BorderLayout(10, 5));

        // 左侧包含薪资输入
        JPanel leftPanel = new JPanel(new BorderLayout(5, 0));
        salaryField = new JTextField(config.getProperty("salary", "8000"), 8);
        salaryField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        salaryField.setPreferredSize(new Dimension(100, 35));
        leftPanel.add(new JLabel("薪资金额："), BorderLayout.WEST);
        leftPanel.add(salaryField, BorderLayout.CENTER);
        leftPanel.add(new JLabel("元/"), BorderLayout.EAST);

        // 右侧包含薪资类型
        JPanel rightPanel = new JPanel(new BorderLayout(5, 0));
        salaryTypeCombo = new JComboBox<>(new String[]{"日", "月"});
        salaryTypeCombo.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        salaryTypeCombo.setPreferredSize(new Dimension(60, 30));
        salaryTypeCombo.setSelectedItem(config.getProperty("salaryType", "月"));
        salaryTypeLabel = new JLabel("月薪");
        salaryTypeLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        salaryTypeLabel.setForeground(new Color(52, 152, 219));
        salaryTypeCombo.addActionListener(e -> {
            salaryTypeLabel.setText(salaryTypeCombo.getSelectedIndex() == 0 ? "日薪" : "月薪");
        });

        rightPanel.add(salaryTypeLabel, BorderLayout.WEST);
        rightPanel.add(salaryTypeCombo, BorderLayout.CENTER);

        // 组合左右面板
        salaryPanel.add(leftPanel, BorderLayout.CENTER);
        salaryPanel.add(rightPanel, BorderLayout.EAST);

        // 工作时间设置
        JPanel timePanel = new JPanel(new GridLayout(2, 1, 5, 5));

        // 日工作时间
        JPanel hoursPanel = new JPanel(new BorderLayout(10, 0));
        // 从配置读取日工作时间，默认值使用8
        workHoursSpinner = new JSpinner(new SpinnerNumberModel(
                Integer.parseInt(config.getProperty("dailyWorkHours", "8")), // 读取配置值
                1, 24, 1));
        workHoursSpinner.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        JSpinner.NumberEditor hoursEditor = new JSpinner.NumberEditor(workHoursSpinner, "#");
        workHoursSpinner.setEditor(hoursEditor);
        hoursEditor.getTextField().setColumns(2);
        hoursEditor.getTextField().setPreferredSize(new Dimension(20, 25));
        hoursPanel.add(new JLabel("天工作时间："), BorderLayout.WEST);
        hoursPanel.add(workHoursSpinner, BorderLayout.CENTER);
        hoursPanel.add(new JLabel("小时"), BorderLayout.EAST);

        // 月工作天数
        JPanel daysPanel = new JPanel(new BorderLayout(10, 0));
        // 从配置读取月工作天数，默认值使用21.75
        workDaysSpinner = new JSpinner(new SpinnerNumberModel(
                Double.parseDouble(config.getProperty("monthlyWorkDays", "21.75")), // 读取配置值
                1, 31, 0.5));
        workDaysSpinner.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        JSpinner.NumberEditor daysEditor = new JSpinner.NumberEditor(workDaysSpinner, "#.##");
        workDaysSpinner.setEditor(daysEditor);
        daysEditor.getTextField().setColumns(4);
        daysEditor.getTextField().setPreferredSize(new Dimension(30, 25));
        daysPanel.add(new JLabel("月工作天数："), BorderLayout.WEST);
        daysPanel.add(workDaysSpinner, BorderLayout.CENTER);
        daysPanel.add(new JLabel("天"), BorderLayout.EAST);

        timePanel.add(hoursPanel);
        timePanel.add(daysPanel);

        // 添加所有面板
        int panelHeight = 120;
        salaryPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, panelHeight));
        timePanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, panelHeight));

        panel.add(salaryPanel);
        panel.add(Box.createVerticalStrut(10)); // 保留间距
        panel.add(timePanel);
        panel.add(Box.createVerticalStrut(5)); // 减小底部间距

        return panel;
    }

    private JPanel createEarningsPanel() {
        JPanel panel = new JPanel(new GridLayout(3, 1, 5, 5)); // 改为3行1列布局 // 修改行间距为10，增加底部距离
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(46, 204, 113), 1),
                "收入统计",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 14),
                new Color(46, 204, 113)
        ));

        todayEarningsLabel = new JLabel("今日收入：¥0.00");
        todayEarningsLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        monthlyEarningsLabel = new JLabel("本月累计：¥0.00");
        monthlyEarningsLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));

        // 每小时、每分钟、每秒收益标签
        hourlyEarningsLabel = new JLabel("时薪：¥0.000");
        hourlyEarningsLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        minuteEarningsLabel = new JLabel("分薪：¥0.000");
        minuteEarningsLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        secondEarningsLabel = new JLabel("秒薪：¥0.000");
        secondEarningsLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));

        // 创建子面板用于显示每小时、每分钟、每秒收益
        JPanel ratePanel = new JPanel(new GridLayout(1, 3, 0, 0)); // 移除垂直间距
        ratePanel.setBackground(new Color(240, 240, 240)); // 设置背景色与父面板一致
        ratePanel.add(hourlyEarningsLabel);
        ratePanel.add(minuteEarningsLabel);
        ratePanel.add(secondEarningsLabel);

        panel.add(todayEarningsLabel);
        panel.add(monthlyEarningsLabel);
        panel.add(ratePanel);

        updateEarningsRates();

        // 设置最大宽度
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel.getPreferredSize().height));
        return panel;
    }

    private JPanel createControlPanel() {
        // 主面板使用GridLayout，2行3列，使上下按钮对齐
        JPanel mainPanel = new JPanel(new GridLayout(2, 3, 10, 10));

        // 开始按钮
        startButton = new JButton("开始上班！");
        startButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        startButton.setBackground(new Color(46, 204, 113));
        startButton.setForeground(Color.WHITE);
        startButton.setFocusPainted(false);
        startButton.addActionListener(e -> startWork()); // 添加事件监听器

        // 暂停按钮
        pauseButton = new JButton("休息");
        pauseButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        pauseButton.setBackground(new Color(241, 196, 15));
        pauseButton.setForeground(Color.WHITE);
        pauseButton.setFocusPainted(false);
        pauseButton.addActionListener(e -> pauseWork()); // 添加事件监听器

        // 结束按钮
        endButton = new JButton("下班！");
        endButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        endButton.setBackground(new Color(231, 76, 60));
        endButton.setForeground(Color.WHITE);
        endButton.setFocusPainted(false);
        endButton.addActionListener(e -> endWork()); // 添加事件监听器

        // 置顶按钮
        toggleTopButton = new JButton("界面置顶");
        toggleTopButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        toggleTopButton.setBackground(new Color(52, 152, 219));
        toggleTopButton.setForeground(Color.WHITE);
        toggleTopButton.setFocusPainted(false);
        toggleTopButton.addActionListener(e -> toggleWindowTop());

        // 小窗显示按钮
        miniWindowButton = new JButton("小窗显示");
        miniWindowButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        miniWindowButton.setBackground(new Color(155, 89, 182));
        miniWindowButton.setForeground(Color.WHITE);
        miniWindowButton.setFocusPainted(false);
        miniWindowButton.addActionListener(e -> toggleMiniWindow());

        // 设置按钮
        JButton settingsButton = new JButton("设置");
        settingsButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        settingsButton.setBackground(new Color(255, 182, 185));
        settingsButton.setForeground(Color.WHITE);
        settingsButton.setFocusPainted(false);
        settingsButton.addActionListener(e -> openSettingsDialog());

        // 添加按钮到面板
        mainPanel.add(startButton);
        mainPanel.add(pauseButton);
        mainPanel.add(endButton);
        mainPanel.add(toggleTopButton);
        mainPanel.add(miniWindowButton);
        mainPanel.add(settingsButton);

        // 设置最大宽度
        mainPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, mainPanel.getPreferredSize().height));
        return mainPanel;
    }

    private void setupTimer() {
        updateTimer = new Timer(1000, e -> updateDisplay());
    }

    public void startWork() {
        try {
            // 获取输入值
            double salary = Double.parseDouble(salaryField.getText().trim());
            boolean isMonthly = salaryTypeCombo.getSelectedIndex() == 1;
            int workHours = (Integer) workHoursSpinner.getValue();

            // 从微调器获取月工作天数配置值
            double monthlyWorkDays = (Double) workDaysSpinner.getValue();

            // 设置计算器
            calculator.setSalaryInfo(salary, isMonthly, workHours, monthlyWorkDays);
            calculator.startWork();

            // 更新UI状态
            updateButtonStates(true);

            // 禁用输入
            salaryTypeCombo.setEnabled(false);
            salaryField.setEnabled(false);
            workHoursSpinner.setEnabled(false);
            workDaysSpinner.setEnabled(false);
            salaryTypeLabel.setEnabled(false);

            // 启动定时器
            updateTimer.start();

        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this,
                    "请输入有效的薪资金额！",
                    "输入错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    public void pauseWork() {
        // 先暂停计时器和工作状态
        updateTimer.stop();
        calculator.pauseWork();
        
        // 获取暂停后的收益值
        double todayEarnings = calculator.calculateCurrentEarnings();
        
        startButton.setText("继续工作");
        updateButtonStates(false);

        calculator.setCurrentDailyEarnings(todayEarnings);

        // 更新显示确保数据同步
        updateDisplay();
    }

    public void endWork() {
        // 下班确认弹窗
        int confirm = JOptionPane.showConfirmDialog(this,
                "确认下班？\n确认下班后，再次点击开始上班时日薪将会从0开始计算；同时会保留月累计薪资。",
                "确认下班",
                JOptionPane.YES_NO_OPTION);
        
        if (confirm != JOptionPane.YES_OPTION) {
            return; // 用户取消下班
        }

        // 当未开始工作且今日总工作时间为0时提示
        if (!calculator.isWorking() && calculator.getTotalWorkTimeToday() == 0) {
            JOptionPane.showMessageDialog(this,
                    "今日尚未开始工作！",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        calculator.endWork();
        updateTimer.stop();

        // 保存当前月份的累计收入
        String currentMonth = LocalDate.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM"));
        double currentMonthlyEarnings = calculator.getMonthlyEarnings();
        MonthlyEarningsRecorder.saveEarnings(currentMonth, currentMonthlyEarnings);

        // 获取并显示最终当日收入
        double finalTodayEarnings = calculator.getTodayFinalEarnings();
        todayEarningsLabel.setText("今日收入：" + decimalFormat.format(finalTodayEarnings));

        // 立即更新月度显示数值
        monthlyEarningsLabel.setText("本月累计：" + decimalFormat.format(currentMonthlyEarnings));

        calculator.setCurrentDailyEarnings(finalTodayEarnings);

        // 更新显示确保数据同步
        updateDisplay();

        // 重置按钮文本
        startButton.setText("开始上班！");

        // 启用输入
        salaryTypeCombo.setEnabled(true);
        salaryField.setEnabled(true);
        workHoursSpinner.setEnabled(true);
        workDaysSpinner.setEnabled(true);
        salaryTypeLabel.setEnabled(true);

        // 重置计算器状态
        calculator.reset();  // 重置计算器状态

        logger.info("finalTodayEarnings: " + finalTodayEarnings + ", currentMonthlyEarnings: " + currentMonthlyEarnings);

        // 显示工作结束提示
        JOptionPane.showMessageDialog(this,
                "今日工作结束！\n" +
                        "今日收入：" + decimalFormat.format(calculator.getTodayFinalEarnings()) + "\n" +
                        "本月累计：" + decimalFormat.format(currentMonthlyEarnings),
                "工作结束",
                JOptionPane.INFORMATION_MESSAGE);

        // 重置按钮状态到初始状态
        updateButtonStates(false);  // 确保下班后恢复按钮初始状态
    }

    private void updateButtonStates(boolean isWorking) {
        startButton.setEnabled(!isWorking);
        pauseButton.setEnabled(isWorking);
        // 下班按钮始终保持可用状态
        endButton.setEnabled(true);
    }

    private void updateDisplay() {
        // 更新今日收入
        double todayEarnings = calculator.isWorking() ? 
                calculator.calculateCurrentEarnings() : 
                calculator.getTodayFinalEarnings();

        if (Double.isNaN(todayEarnings) || Double.isInfinite(todayEarnings)) {
            todayEarnings = 0.0;
        }
        todayEarningsLabel.setText("今日收入：" + decimalFormat.format(todayEarnings));

        // 无论是否在工作状态，都使用getMonthlyEarnings()获取保存的月度累计值
        double monthlyEarnings = calculator.getMonthlyEarnings() +
                (calculator.isPause()
                        ? calculator.calculateCurrentEarnings()
                        : (calculator.isWorking() ? calculator.calculateCurrentEarnings() : 0));

        if (Double.isNaN(monthlyEarnings) || Double.isInfinite(monthlyEarnings)) {
            monthlyEarnings = 0.0;
        }
        monthlyEarningsLabel.setText("本月累计：" + decimalFormat.format(monthlyEarnings));

        logger.info("update >>> todayEarnings: " + todayEarnings + ", monthlyEarnings: " + monthlyEarnings);

        // 同步更新小窗口数据
        if (miniWindow != null && miniWindow.isVisible()) {
            miniWindow.updateEarnings(todayEarnings);
        }
    }

    /**
     * 更新时薪、分薪、秒薪的显示
     */
    private void updateEarningsRates() {
        double hourlyRate = calculator.getHourlyRate();
        double minuteRate = hourlyRate / 60;
        double secondRate = minuteRate / 60;

        DecimalFormat threeDecimalFormat = new DecimalFormat("¥#,##0.000");
        hourlyEarningsLabel.setText("时薪：" + threeDecimalFormat.format(hourlyRate));
        minuteEarningsLabel.setText("分薪：" + threeDecimalFormat.format(minuteRate));
        secondEarningsLabel.setText("秒薪：" + threeDecimalFormat.format(secondRate));

        logger.info("hourly wage：" + hourlyRate + ", minute wage：" + minuteRate + ", second wage：" + secondRate);
    }

    /**
     * 切换窗口置顶状态
     */
    private void toggleWindowTop() {
        isWindowTop = !isWindowTop;
        try {
            super.setAlwaysOnTop(isWindowTop);
            if (isWindowTop) {
                toggleTopButton.setBackground(new Color(48, 227, 202));
                toggleTopButton.setText("取消置顶");
                if (miniWindow != null) {
                    miniWindow.setWindowTop(true);
                    logger.info("Cancel window topping");
                }
            } else {
                toggleTopButton.setBackground(new Color(52, 152, 219));
                toggleTopButton.setText("界面置顶");
                if (miniWindow != null) {
                    miniWindow.setWindowTop(false);
                    logger.info("Window top");
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,
                    "窗口置顶设置失败: " + e.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            isWindowTop = !isWindowTop; // 恢复状态
        }
    }

    /**
     * 切换小窗口显示状态
     */
    private void toggleMiniWindow() {
        try {
            if (miniWindow == null) {
                miniWindow = new MiniEarningsWindow(this);
                // 确保小窗口同步主窗口的置顶状态
                miniWindow.setWindowTop(isWindowTop);

                // 在小窗口初始化时同步主窗口的收益数据
                double todayEarnings = calculator.isWorking() ?
                        calculator.calculateCurrentEarnings() : calculator.getTodayFinalEarnings();
                miniWindow.updateEarnings(todayEarnings);
            }

            if (miniWindow != null && miniWindow.isVisible()) {
                miniWindow.dispose();  // 销毁小窗口
                miniWindow = null;     // 清除引用
                miniWindowButton.setBackground(new Color(155, 89, 182));
                setVisible(true);      // 显示主窗口
            } else {
                // 更新小窗口数据（未开始工作时显示0）
                double todayEarnings = calculator.isWorking() ?
                        calculator.calculateCurrentEarnings() : calculator.getTodayFinalEarnings();
                miniWindow.updateEarnings(todayEarnings);

                // 设置小窗口位置在主窗口右下角
                Point mainLocation = getLocation();
                Dimension mainSize = getSize();
                miniWindow.setLocation(
                        mainLocation.x + mainSize.width - 50,
                        mainLocation.y + mainSize.height - 50
                );

                // 同步置顶状态
                miniWindow.setWindowTop(isWindowTop);

                // 显示小窗口，隐藏主窗口
                miniWindow.setVisible(true);
                setVisible(false);
                miniWindowButton.setBackground(new Color(142, 68, 173));
                logger.info("mini window initialization completed");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,
                    "小窗口操作失败: " + e.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            if (miniWindow != null) {
                miniWindow.dispose();
                miniWindow = null;
            }
        }
    }

    private void addConfigChangeListeners() {
        salaryField.getDocument().addDocumentListener(new DocumentListener() {
            public void changedUpdate(DocumentEvent e) {
                saveCurrentConfig();
                updateCalculator();
                updateEarningsRates();
            }

            public void insertUpdate(DocumentEvent e) {
                saveCurrentConfig();
                updateCalculator();
                updateEarningsRates();
            }

            public void removeUpdate(DocumentEvent e) {
                saveCurrentConfig();
                updateCalculator();
                updateEarningsRates();
            }
        });

        salaryTypeCombo.addActionListener(e -> {
            saveCurrentConfig();
            updateCalculator();
            updateEarningsRates();
        });

        workHoursSpinner.addChangeListener(e -> {
            saveCurrentConfig();
            updateCalculator();
            updateEarningsRates();
        });

        workDaysSpinner.addChangeListener(e -> {
            saveCurrentConfig();
            updateCalculator();
            updateEarningsRates();
        });
    }

    // 更新calculator实例的方法
    private void updateCalculator() {
        try {
            double salary = Double.parseDouble(salaryField.getText().trim());
            boolean isMonthly = salaryTypeCombo.getSelectedIndex() == 1;
            int workHours = (Integer) workHoursSpinner.getValue();
            double monthlyWorkDays = (Double) workDaysSpinner.getValue();
            calculator.setSalaryInfo(salary, isMonthly, workHours, monthlyWorkDays);
        } catch (NumberFormatException ex) {
            // 忽略无效输入
        }
    }

    private void saveCurrentConfig() {
        Properties props = new Properties();
        props.setProperty("salary", salaryField.getText());
        props.setProperty("salaryType", (String) salaryTypeCombo.getSelectedItem());
        props.setProperty("dailyWorkHours", workHoursSpinner.getValue().toString());
        props.setProperty("monthlyWorkDays", workDaysSpinner.getValue().toString());
        ConfigManager.saveConfig(props);
    }

    // 自定义月累计薪资
    private void openSettingsDialog() {
        // 检查是否正在上班
        if (calculator.isWorking()) {
            JOptionPane.showMessageDialog(this, 
                "上班期间不支持修改月累计薪资！\n请先结束当天工作再进行设置。", 
                "操作受限", 
                JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 创建面板包含输入框和说明文字
        JPanel panel = new JPanel(new BorderLayout());
        JLabel label = new JLabel("自定义本月累计薪资：");
        JTextField textField = new JTextField(15);
        JLabel infoLabel = new JLabel("月累计薪资 = 自定义月累计薪资 + 当日实时日薪");
        infoLabel.setFont(new Font("微软雅黑", Font.PLAIN, 10));
        infoLabel.setForeground(Color.GRAY);
        
        panel.add(label, BorderLayout.NORTH);
        panel.add(textField, BorderLayout.CENTER);
        panel.add(infoLabel, BorderLayout.SOUTH);
        
        int result = JOptionPane.showConfirmDialog(this, panel, "设置月累计薪资", 
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        
        if (result == JOptionPane.OK_OPTION) {
            String input = textField.getText();
            if (input != null && !input.trim().isEmpty()) {
                try {
                    double customMonthlyEarnings = Double.parseDouble(input.trim());
                    if (customMonthlyEarnings < 0) {
                        throw new NumberFormatException();
                    }
                    // 计算输入的月累计薪资后，和当日累计薪资进行相加
                    double newMonthlyEarningsdisplay = customMonthlyEarnings + calculator.getCurrentDailyEarnings();
                    monthlyEarningsLabel.setText("本月累计：" + decimalFormat.format(newMonthlyEarningsdisplay));
                    // 保存更新的月累计薪资到calculator实例中
                    calculator.setInitialMonthlyEarnings(customMonthlyEarnings);
                    // 获取当前月分，保存月累计薪资到文件中
                    String currentMonth = LocalDate.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM"));
                    MonthlyEarningsRecorder.saveCustomEarnings(currentMonth, customMonthlyEarnings);
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this, "请输入有效的正数金额！", "输入错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }
}
